package com.travel.server.manager.impl.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.travel.common.CommonConstant;
import com.travel.common.base.BaseResponse;
import com.travel.common.exception.WorkCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: LiZhenhui
 * @Date: 2018/10/17 17:57
 * @Desc:
 */
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

    private final String CONTENT_TYPE = "application/json;charset=utf-8";

    /**
     * 登录url
     */
    private final String LOGIN_URL = "/login";

    /**
     * 刷新验证码url
     */
    private final String REFRESH_VERIFY_CODE_URL = "/refresh_verify_code";

    private final String MSG_NOTIFY_URL = "/receive_result";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //判断当前url，登录和刷新验证码不校验session
        String requestUri = request.getRequestURI();
        if(requestUri.contains(LOGIN_URL) || requestUri.contains(REFRESH_VERIFY_CODE_URL) || requestUri.contains(MSG_NOTIFY_URL)){
            return true;
        }
        //判断session是否登录态
        Object userObj = request.getSession().getAttribute(CommonConstant.SESSION_USER_INFO);
        if(userObj == null) {
            writeTimeoutResponse(response);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private void writeTimeoutResponse(HttpServletResponse response){
        response.setContentType(CONTENT_TYPE);
        PrintWriter writer = null;
        try {
            BaseResponse baseResponse = BaseResponse.makeError(WorkCode.LOGIN_TIME_OUT);
            baseResponse.setReLogin(true);
            writer = response.getWriter();
            writer.print(JSONObject.toJSONString(baseResponse));

        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
